/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.easy.web.filter;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.easy.core.constant.SecurityConstants;
import com.easy.core.exception.GlobalResultInfoEnum;
import com.easy.web.utils.ResponseUtil;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 只有请求头携带了 spring-boot-admin-service ，才能访问actuator相关功能接口
 *
 * @author Jasmine
 * @since 1.0.0
 */
@Component
@WebFilter
public class ActuatorFilter implements Filter {
    @Value("${spring.boot.admin.client.port:8081}")
    private String adminServicePort;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        // 判断约定好的请求头参数
        if (request.getRequestURI().contains("/actuator")
            && !adminServicePort.equals(request.getHeader(SecurityConstants.ACTUATOR_HEADERNAME))) {
            // FIXME 记录日志 将ip 超过多次加入黑名单
            ResponseUtil.responseWriter(response, GlobalResultInfoEnum.FAILED.getCode(), "抱歉，你无权限访问，Actuator端口受保护！");
            return;
            // 抛出异常，这里异常不能被全局异常处理器拦截，需要自定义一个 controller
            /*  throw new RuntimeException("抱歉，你无权限访问，Actuator端口受保护！ Sorry, you have no permission to access
            it，Actuator " +
                    "port protected！");*/
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
